﻿using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Dapper;

namespace LabelPrint.Util
{
    public class DbUtil
    {
        public static string DbConnectionName = "Product_DB";

        public static IDbConnection GetConnection()
        {
            var conn = new SqlConnection(ConfigurationManager.ConnectionStrings[DbConnectionName].ConnectionString);
            if (conn.State != ConnectionState.Open)
                conn.Open();
            return conn;
        }

        public static IDbConnection GetConnection(string conStr)
        {
            var con = new SqlConnection(conStr);
            if (con.State != ConnectionState.Open)
                con.Open();
            return con;
        }

        public static IEnumerable<T> Query<T>(string sql, object param)
        {
            using (IDbConnection conn = GetConnection())
            {
                return conn.Query<T>(sql, param);
            }
        }

        public static IEnumerable<T> Query<T>(string sql, object param, CommandType commandType)
        {
            using (IDbConnection conn = GetConnection())
            {
                return conn.Query<T>(sql, param, commandType: commandType);
            }
        }

        public static int Execute(string sql, object param)
        {
            using (IDbConnection conn = GetConnection())
            {
                return conn.Execute(sql, param);
            }
        }
    }
}